<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网上书店 - 书籍管理系统</title>
    <script src="js/vue.global.js"></script>
    <!-- 引入Bootstrap 5样式 -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
            padding: 20px;
        }
        .header {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            padding: 30px 0;
            border-radius: 10px;
            margin-bottom: 30px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .book-card {
            transition: transform 0.3s, box-shadow 0.3s;
            margin-bottom: 20px;
            border: none;
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        .book-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .btn-add {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            border: none;
            border-radius: 50px;
            padding: 10px 25px;
            font-weight: 600;
            margin-bottom: 20px;
        }
        .btn-delete {
            background: linear-gradient(135deg, #ff416c 0%, #ff4b2b 100%);
            border: none;
            border-radius: 20px;
        }
        .btn-search {
            background: linear-gradient(135deg, #00b09b 0%, #96c93d 100%);
            border: none;
            border-radius: 50px;
            padding: 10px 25px;
            font-weight: 600;
        }
        .form-container {
            background-color: white;
            border-radius: 10px;
            padding: 25px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            margin-bottom: 30px;
        }
        .search-container {
            background-color: white;
            border-radius: 10px;
            padding: 25px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            margin-bottom: 30px;
        }
        .empty-state {
            text-align: center;
            padding: 40px;
            color: #6c757d;
        }
        .loading {
            text-align: center;
            padding: 20px;
        }
        .alert {
            border-radius: 10px;
            border: none;
        }
        .search-results-info {
            margin-bottom: 15px;
            color: #6c757d;
            font-style: italic;
        }
        /* 在style标签中添加 */
        .book-image-container {
            height: 200px;
            overflow: hidden;
            border-top-left-radius: 10px;
            border-top-right-radius: 10px;
        }
        .book-image-preview {
            max-width: 100px;
            max-height: 100px;
            object-fit: cover;
            border-radius: 5px;
            margin-top: 10px;
        }
    </style>
</head>
<body>
<div id="app">
    <!-- 页面标题 -->
    <div class="header text-center">
        <h1>网上书店 - 书籍管理系统</h1>
        <p class="lead">轻松管理您的图书库存</p>
    </div>

    <div class="container">
        <!-- 消息提示 -->
        <div v-if="message" :class="['alert', messageType === 'success' ? 'alert-success' : 'alert-danger']">
            {{ message }}
        </div>

        <!-- 搜索框 -->
        <div class="search-container">
            <h3>搜索书籍</h3>
            <form @submit.prevent="searchBooks">
                <div class="row">
                    <div class="col-md-8">
                        <div class="mb-3">
                            <label for="searchKey" class="form-label">关键字</label>
                            <input type="text" class="form-control" id="searchKey" v-model="searchKey" placeholder="输入书名或描述进行搜索">
                        </div>
                    </div>
                    <div class="col-md-4 d-flex align-items-end">
                        <button type="submit" class="btn btn-search w-100" :disabled="loading">
                            <span v-if="loading" class="spinner-border spinner-border-sm" role="status"></span>
                            {{ loading ? '搜索中...' : '搜索书籍' }}
                        </button>
                    </div>
                </div>
            </form>
            <div v-if="searchPerformed && books.length > 0" class="search-results-info">
                找到 {{ books.length }} 本相关书籍
            </div>
        </div>

        <!-- 添加书籍表单 -->
        <div class="form-container">
            <h3>添加新书籍</h3>
            <form @submit.prevent="addBook">
                <div class="row">
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label for="bookName" class="form-label">书名</label>
                            <input type="text" class="form-control" id="bookName" v-model="newBook.name" required>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label for="bookPrice" class="form-label">价格</label>
                            <input type="number" class="form-control" id="bookPrice" v-model="newBook.price" min="0" step="0.01" required>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label for="bookDesc" class="form-label">描述</label>
                            <input type="text" class="form-control" id="bookDesc" v-model="newBook.desc">
                        </div>
                    </div>
                </div>
                <!-- 在添加书籍表单中增加图片上传字段 -->
                <div class="col-md-4">
                    <div class="mb-3">
                        <label for="bookImage" class="form-label">书籍图片</label>
                        <input type="file" class="form-control" id="bookImage" @change="handleImageUpload" accept="image/*">
                        <div class="form-text">支持 JPG, PNG 格式，大小不超过 2MB</div>
                    </div>
                </div>
                <!-- 在图片上传字段后添加预览 -->
                <div v-if="imagePreview" class="mt-2">
                    <img :src="imagePreview" alt="预览" class="book-image-preview">
                </div>

                <button type="submit" class="btn btn-add" :disabled="loading">
                    <span v-if="loading" class="spinner-border spinner-border-sm" role="status"></span>
                    {{ loading ? '添加中...' : '添加书籍' }}
                </button>
            </form>
        </div>

        <!-- 书籍列表 -->
        <div class="books-section">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h3>书籍列表</h3>
                <button v-if="searchPerformed" class="btn btn-outline-secondary" @click="resetSearch">
                    显示全部书籍
                </button>
            </div>

            <div v-if="loading" class="loading">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                <p class="mt-2">正在加载书籍数据...</p>
            </div>

            <div v-else-if="books.length === 0" class="empty-state">
                <h4 v-if="searchPerformed">未找到相关书籍</h4>
                <h4 v-else>暂无书籍</h4>
                <p>点击上方"添加书籍"按钮开始添加书籍到库存</p>
            </div>

            <div v-else class="row">
                <div class="col-md-6 col-lg-4" v-for="book in books" :key="book.id">
                    <div class="card book-card">
                        <div class="card-body">
                            <h5 class="card-title">{{ book.name }}</h5>
                            <p class="card-text text-muted">{{ book.desc || '暂无描述' }}</p>
                            <div class="d-flex justify-content-between align-items-center">
                                <span class="h5 text-primary">¥{{ book.price }}</span>
                                <button class="btn btn-delete btn-sm" @click="deleteBook(book.id)" :disabled="deletingId === book.id">
                                    <span v-if="deletingId === book.id" class="spinner-border spinner-border-sm" role="status"></span>
                                    {{ deletingId === book.id ? '删除中...' : '删除' }}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    const { createApp, ref, onMounted } = Vue;

    createApp({
        setup() {
            // 响应式数据
            const books = ref([]);
            const loading = ref(false);
            const deletingId = ref(null);
            const message = ref('');
            const messageType = ref('success');
            const searchKey = ref('');
            const searchPerformed = ref(false);

            // 新书籍数据
            const newBook = ref({
                name: '',
                price: 0,
                desc: ''
            });
            // 在setup函数中添加
            const bookImage = ref(null);
            const imagePreview = ref('');

// 处理图片上传
            const handleImageUpload = (event) => {
                const file = event.target.files[0];
                if (file) {
                    // 验证文件类型
                    if (!file.type.startsWith('image/')) {
                        showMessage('请选择图片文件', 'danger');
                        event.target.value = '';
                        return;
                    }

                    // 验证文件大小（2MB）
                    if (file.size > 2 * 1024 * 1024) {
                        showMessage('图片大小不能超过 2MB', 'danger');
                        event.target.value = '';
                        return;
                    }

                    bookImage.value = file;

                    // 生成预览
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        imagePreview.value = e.target.result;
                    };
                    reader.readAsDataURL(file);
                }
            };

            // 显示消息
            const showMessage = (text, type = 'success') => {
                message.value = text;
                messageType.value = type;
                setTimeout(() => {
                    message.value = '';
                }, 3000);
            };

            // 获取书籍列表
            const fetchBooks = async () => {
                loading.value = true;
                try {
                    const response = await fetch('/book/search');
                    if (!response.ok) {
                        throw new Error('获取书籍列表失败');
                    }
                    const re =  await response.json();
                    if(re.success) {
                        books.value = re.data;
                    }else{
                        alert(re.message)
                    }
                } catch (error) {
                    console.error('Error fetching books:', error);
                    showMessage('获取书籍列表失败: ' + error.message, 'danger');
                } finally {
                    loading.value = false;
                }
            };

            // 搜索书籍
            const searchBooks = async () => {
                if (!searchKey.value.trim()) {
                    showMessage('请输入搜索关键字', 'danger');
                    return;
                }

                loading.value = true;
                try {
                    const response = await fetch(`/book/search?keyword=${encodeURIComponent(searchKey.value)}`);
                    if (!response.ok) {
                        throw new Error('搜索书籍失败');
                    }
                    const re =  await response.json();
                    if(re.success) {
                        books.value = re.data;
                        searchPerformed.value = true;
                    } else {
                        alert(re.message);
                    }
                } catch (error) {
                    console.error('Error searching books:', error);
                    showMessage('搜索书籍失败: ' + error.message, 'danger');
                } finally {
                    loading.value = false;
                }
            };

            // 重置搜索
            const resetSearch = () => {
                searchKey.value = '';
                searchPerformed.value = false;
                fetchBooks();
            };

            // 修改addBook函数
            const addBook = async () => {
                loading.value = true;
                try {
                    // 创建FormData对象，支持文件上传
                    const formData = new FormData();
                    formData.append('name', newBook.value.name);
                    formData.append('price', newBook.value.price);

                    if (newBook.value.desc) {
                        formData.append('desc', newBook.value.desc);
                    }

                    if (bookImage.value) {
                        formData.append('image', bookImage.value);
                    }

                    const response = await fetch('/book/create', {
                        method: 'POST',
                        body: formData
                        // 注意：使用FormData时不要设置Content-Type，浏览器会自动设置
                    });

                    const re = await response.json();
                    alert(re.message);

                    // 清空表单和图片
                    newBook.value = { name: '', price: 0, desc: '' };
                    bookImage.value = null;
                    imagePreview.value = '';
                    // 清空文件输入框
                    document.getElementById('bookImage').value = '';

                    // 重新获取书籍列表
                    await fetchBooks();
                    showMessage('书籍添加成功！');
                } catch (error) {
                    console.error('Error adding book:', error);
                    showMessage('添加书籍失败: ' + error.message, 'danger');
                } finally {
                    loading.value = false;
                }
            };
            // 删除书籍
            const deleteBook = async (id) => {
                if (!confirm('确定要删除这本书吗？')) {
                    return;
                }

                deletingId.value = id;
                try {
                    const response = await fetch(`/book/remove?id=${id}`);

                    const re =  await response.json();

                    alert(re.message)

                    // 重新获取书籍列表
                    await fetchBooks();

                    showMessage('书籍删除成功！');
                } catch (error) {
                    console.error('Error deleting book:', error);
                    showMessage('删除书籍失败: ' + error.message, 'danger');
                } finally {
                    deletingId.value = null;
                }
            };

            // 组件挂载后获取书籍列表
            onMounted(() => {
                fetchBooks();
            });

            return {
                books,
                loading,
                deletingId,
                message,
                messageType,
                newBook,
                searchKey,
                searchPerformed,
                addBook,
                deleteBook,
                searchBooks,
                resetSearch,
                handleImageUpload,
                imagePreview
            };
        }
    }).mount('#app');
</script>
</body>
</html>